package com.shixianjun.tools;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class Tools {
    public static int[] randomIntArray(int length, int maxValue) {
        return randomIntArray(length, maxValue, true);
    }

    public static int[] randomIntArray(int length, int maxValue, boolean repeatable) {
        return randomIntArray(length, maxValue, repeatable, false);
    }

    public static int[] randomIntArray(int length, int maxValue, boolean repeatable, boolean sorted) {

        int[] arr = new int[length];
        if (repeatable) {
            for (int i = 0; i < length; i++) {
                arr[i] = (int) (Math.random() * maxValue) + 1;
            }
        } else {
            if (maxValue < length) {
                System.out.print("⚠️不可重复时，最大值不可以小于长度，最大值已更改为长度值！\n");
                maxValue = length;
            }
            Set<Integer> set = new HashSet<Integer>();
            while (set.size() < length) {
                set.add((int) (Math.random() * maxValue) + 1);
            }
            Integer[] arrTemporary = new Integer[set.size()];
            set.toArray(arrTemporary);
            arr = Arrays.stream(arrTemporary).mapToInt(Integer::intValue).toArray();
        }

        if (sorted) {
            Arrays.sort(arr);
        }
        return arr;
    }

    public static <T> void swap(T[] arr, int i, int j) {
        if (i == j) return;

        T tem = arr[i];
        arr[i] = arr[j];
        arr[j] = tem;
    }

    public static void printIntArray(String title, int[] arr) {
        System.out.print(title + ": ");
        for (int i = 0; i < arr.length; i++) {
            System.out.printf(" %02d", arr[i]);
        }
        System.out.print("\n");
    }

//    public static void printElapsedTime(String title, Function<String, String> func) {
//        long start = System.currentTimeMillis();
//        func.apply(title);
//        long end = System.currentTimeMillis();
//        System.out.print(title + "耗时: " + (end - start) + "毫秒\n");
//    }
}
